﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyMusicList.DBModel
{
    public class DataDBContext : DbContext
    {
        public DataDBContext(DbContextOptions<DataDBContext> options)
            : base(options)
        {

        }

        public DataDBContext()
            : base()
        {

        }

        //mysql数据库中有bit数据类型
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            foreach (var entityType in builder.Model.GetEntityTypes())
            {
                foreach (var property in entityType.GetProperties())
                {
                    if (property.ClrType == typeof(bool))
                    {
                        property.SetValueConverter(new BoolToIntConverter());
                    }
                }
            }
        }

        /// <summary>
        /// 系统总歌库
        /// </summary>
        public DbSet<Sys_Music> Sys_Music { get; set; }
        /// <summary>
        /// 用户歌单
        /// </summary>
        public DbSet<User_Music> User_Music { get; set; }

        /// <summary>
        /// 用户
        /// </summary>
        public DbSet<User> User { get; set; }

        /// <summary>
        /// 用户
        /// </summary>
        public DbSet<User_Type> User_Type { get; set; }

        /// <summary>
        /// 歌曲类型
        /// </summary>
        public DbSet<Sys_Music_Type> Sys_Music_Type { get; set; }
    }

    public class BoolToIntConverter : ValueConverter<bool, int>
    {
        public BoolToIntConverter(ConverterMappingHints mappingHints = null)
            : base(
                  v => Convert.ToInt32(v),
                  v => Convert.ToBoolean(v),
                  mappingHints)
        {
        }

        public static ValueConverterInfo DefaultInfo { get; }
            = new ValueConverterInfo(typeof(bool), typeof(int), i => new BoolToIntConverter(i.MappingHints));
    }
}
